import { ref, watch, nextTick, computed } from 'vue'
export default function useFixed(props) {
  const TITLE_HEIGHT = 30
  const groupRef = ref(null)
  const listHeights = ref([])
  const scrollY = ref(0)
  const currentIndex = ref(0)
  const disctance = ref(0)
  const fixedTitle = computed(() => {
    if (scrollY.value < 0) {
      return
    }
    const currentGroup = props.data[currentIndex.value]
    return currentGroup ? currentGroup.title : ''
  })
  const fixedStyle = computed(() => {
    const diff = (disctance.value > 0 && disctance.value < TITLE_HEIGHT) ? disctance.value - TITLE_HEIGHT : 0
    return {
      transform: `translate3d(0, ${diff}px, 0)`
    }
  })
  watch(() => props.data, async() => {
    await nextTick()
    calculate()
  })
  watch(scrollY, (newY) => {
    for (let i = 0; i < listHeights.value.length - 1; i++) {
      const heightTop = listHeights.value[i]
      const heightBottom = listHeights.value[i + 1]
      if (newY >= heightTop && newY <= heightBottom) {
        currentIndex.value = i
        disctance.value = heightBottom - newY
      }
    }
  })

  function calculate() {
    const list = groupRef.value.children
    listHeights.value.length = 0
    let height = 0
    listHeights.value.push(height)
    for (let i = 0; i < list.length; i++) {
      height += list[i].clientHeight
      listHeights.value.push(height)
    }
  }

  function onScroll(pos) {
    scrollY.value = -pos.y
  }
  return {
    groupRef,
    onScroll,
    fixedTitle,
    fixedStyle,
    currentIndex
  }
}